// Dictionary Detail View
// Displays the dictionary detail view in a carousel.
// By swiping right/left, the carousel displays the next/previous dictionary detail view in the list view.
// The carousel is a maximum of 5 cards long ie. the current card and two cards to the left and right
// On a swipe to the next page, a new card is added to the end of the carousel and the first one is
// removed. On a a swipe to the previous page, a new card is added to the start of the carousel and the 
// last one is removed. 
//
// Configuration:
// listView - must be passed in. This is the list that we use to populate the carousel
// selectedItem - the item that was first selected in the list
//
// MDM 14.04.2012

Ext.define('Sencha.view.DictionaryTargetDetailView', {
    extend: 'Ext.Carousel',
    xtype: 'dictionarytargetdetailview',
    requires: [
        'Sencha.view.DictionaryDetailPageView'
    ],
    config: {
        title: 'Dictionary',
        fullscreen: true,
        defaults: {
            styleHtmlContent: true
        },
        indicator: false,
        scrollable: {
           direction: 'vertical',
           directionLock: true
        },
           
        // parameters (passed in)
        listView: null,
        selectedItem: null,
           
        // constants
        carouselSize: 5, // size of the carousel ie. number of cards
        carouselBufferSize: 2, // number of cards to left/right of middle ie. carouselBufferSize/2
           
        // class vars/properties
        activeItemTemp: 2, // Set to same as activeItem. Used to figure out if swiped left or right
        currentListItem: 2, // keeps track of which list item is currently displayed in detail view
        imageURL: null, // store image URL for use later eg. for panel showing detail
           
        listeners: {
           //activeitemchange: 'onActiveItemChange2'
           //itemindexchange: 'onItemIndexChange'
        }
    },
    
    onActiveItemChange2 : function() {
           console.log('onActiveItemChange2 *** ');
    },
           
    /*
    // Create cards. Ideally, if there are enough dictionary entries (in the list view) we want to
    // to display five cards - the current card plus to the left and two to the right
    // Depending on the number of entries in the list view and the item selected though, we may have less
    //
    initialize: function() {
        var listIndex = this.getSelectedItem() - this.getCarouselBufferSize(); // minus two because we have two either side
        var activeItemIndex = Math.floor(this.getCarouselSize()/2); // defaults to the middle 
        //var lastItem = this.getInnerItems().length-1;
        
        // if near start of list and carousel window goes beyond bounds, then start at 0
        if (listIndex<0) {
           listIndex = 0;
        }
    
        // Populate carousel with up to 5 items
        for (i=0; i<this.getCarouselSize(); i++) {
           var record = this.getListView().getStore().getAt(listIndex);
           
           // if this record exists ie. within bounds of the list view
           if (record) {
                // if this is the item clicked on
                if (listIndex == this.getSelectedItem() ) {
                    activeItemIndex = i;
                    this.setActiveItem(i);
                    this.setActiveItemTemp(i); // store for later
                }
           
                // Add card to carousel including HTML content
                //this.add({html: this.getDetailViewHTML( record.get('id') )});
                var newContainer = Ext.create('Sencha.view.DictionaryDetailPageView', {sourceRecord: record});
                this.add(newContainer);

           
                listIndex++;
           }
           // else no more records left in list
           else {
                break;
           }
        }
        
        // Set the active item ie. which card to show
        this.setActiveItem(activeItemIndex);
        // Store the currently active item - used for comparison later
        this.setActiveItemTemp(activeItemIndex);
        // Set the list pointer - used to keep track of which item in the list is displayed in carousel
        this.setCurrentListItem( this.getSelectedItem() );
    },
    */
           
    // Returns Dictionary Detail View HTML
    // dictionarySourceId : id in DictionarySources
    //
    
    getDetailViewHTML: function(dictionarySourceId) {
        var record = Ext.getStore("DictionarySources").getById(dictionarySourceId);
        
        // Get associated DictionaryTarget record using dictionaryTargetId foreign key
        var associatedRecord = Ext.getStore("DictionaryTargets").getById( record.get('dictionaryTargetId') );
           
        if ( associatedRecord.get('imageURL') ) {
           
           
           return '<div class=dictionaryDetail><div class=dictImageThumb><div><img src="' + Sencha.app.getPersistentFileStoreVar() + '/assets/' + associatedRecord.get('imageURL') + '" height="56" /></div></div><div class=dictDetailHeadline><div class=dictDetailTargetWord>' + record.get('targetWord') + '</div><div class=inflection>' + record.get('inflection') + '</div></div><div class=clear></div><div class=dictDetailViewDetailEntry>' + associatedRecord.get('detailedEntry') + '</div></div>';
        }
        // no image for this entry
        else {
           return '<div class=dictionaryDetail><div class=dictDetailHeadline><div class=dictDetailTargetWord>' + record.get('targetWord') + '</div><div class=inflection>' + record.get('inflection') + '</div></div><div class=clear></div><div class=dictDetailViewDetailEntry>' + associatedRecord.get('detailedEntry') + '</div></div>';
        }
    },
    
           
           
    // On swipe to next/previous card, add card to end/start of carousel and remove card from start/end
    //
    onActiveItemChange: function(carousel, newItem, oldItem) {
        // Current item in carousel
        var currentCarouselItem = this.getInnerItems().indexOf( this.getActiveItem() ); 
        var lastCarouselItem = this.getInnerItems().length-1; // last item in carousel
          
        // Set dictionary entry button visibility
        var curRecord = this.getListView().getStore().getAt( this.getCurrentListItem() );   
        if ( curRecord.get('isEditable') == "true"){
           //this.getDictionaryEntryButton().show();
           console.log('show it');
        } else {
           //this.getDictionaryEntryButton().hide();
           console.log('hide it');
        }
         /*  
        // Store imageURL
        var curAssociatedRecord = Ext.getStore("DictionaryTargets").getById( curRecord.get('id') );
        this.setImageURL( curAssociatedRecord.get('imageURL') );
        console.log('stored imageURL = ');
           */
        // if moving to the right
        if ( currentCarouselItem > this.getActiveItemTemp() ) {
           // if the buffer to the right is now less than the carousel buffer size
           if (  ( currentCarouselItem+this.getCarouselBufferSize() ) > lastCarouselItem  ) {
                // Get next record out of carousel bounds
                var record = this.getListView().getStore().getAt( this.getCurrentListItem()+this.getCarouselBufferSize()+1 );
           
                // If there is a record ie. we haven't reached the end of the list
                if (record) {
                    // add new item to carousel
                    //this.add({html: this.getDetailViewHTML( record.get('id') )});
           
           /*
                    var newWord = {
                        xtype: "container",
                        layout:{
                            type:'vbox',
                        },
                        fullscreen: true,
                        //style: 'background-color: #000000;',
                        scrollable: {
                            direction: 'vertical',
                            directionLock: true
                        },
                        items: [
                            {
                                xtype: 'button',
                                text: 'myButton',
                                cls: 'dictionaryImageButton'
                            },
                            {
                                html: this.getDetailViewHTML( record.get('id') )
                            }
                        ]
                    };
            */
           /*
                    // Image container used to display vertically centered image
                    var newWord = {
                        xtype: "container",
                        fullscreen: true,
                        //style: 'background-color: #000000;',
                        scrollable: {
                            direction: 'vertical',
                            directionLock: true
                        },
                        items: [
                            {
                                xtype: 'button',
                                text: 'myButton',
                                cls: 'dictionaryImageButton'
                            },
                            {
                                html: this.getDetailViewHTML( record.get('id') )
                            }
                        ]
                    };
           
                    this.add(newWord);
          */
           
           
           /*
                    // if there is an image, add button
                    var newContainer = Ext.create('Ext.Container', {
                        scrollable: {
                            direction: 'vertical',
                            directionLock: true
                        },
                        
                        items: [
                            {
                                // header container - includes image thumb, target word and speaker button
                                xtype: 'container',
                                name: 'newContainerHeader',
                                layout:{
                                    type:'vbox',
                                    align:'left'
                                },
                                items: [
                                    {
                                        xtype: 'button',
                                        text: 'image button',
                                        cls: 'dictionaryImageButton',
                                        docked: 'left'                                    },
                                    {
                                        
                                        xtype: 'button',
                                        text: 'shouldnt be a button',
                                        cls: 'dictionaryImageButton'
                                    },
                                    {
                                        xtype: 'button',
                                        text: 'speaker button',
                                        cls: 'dictionaryImageButton',
                                        
                                    }
                                ]
                            },
                            {
                                // main body text of dictionary entry
                                html: this.getDetailViewHTML( record.get('id') )    
                            }
                        ],
                                                  
                    
                    });
                    var dictTargetId = record.get('dictionaryTargetId');
                    var associatedRecord = Ext.getStore("DictionaryTargets").getById( dictTargetId );
                    if ( !associatedRecord.get('imageURL') ) {
                        console.log("NO imageURL");
           newContainer.getItems()[0].setHidden(true);
                    } else {
           console.log("THERE is an imageURL");
           newContainer.getItems()[0].setHidden(true);
                    }
           */
           
           //var dictTargetId = record.get('dictionaryTargetId');
           //var associatedRecord = Ext.getStore("DictionaryTargets").getById( dictTargetId );
           
           var newContainer = Ext.create('Sencha.view.DictionaryDetailPageView', {sourceRecord: record});
           this.add(newContainer);
            
            
           /*
                    var associatedRecord = Ext.getStore("DictionaryTargets").getById( record.get('dictionaryTargetId') );
                    if ( associatedRecord.get('imageURL') ) {
                        
                    }
           */
                    // if there is at least the buffer size to the left
                    if ( currentCarouselItem > (this.getCarouselBufferSize()-1) ) {
                        // remove first item in window
                        this.removeInnerAt(0);
                    }
                }
           }
           
           // set current list pointer to the next item in the list
           this.setCurrentListItem( this.getCurrentListItem()+1 );
        }
        // else moving to the left
        else {
           // if the buffer to the left is now less than the carousel buffer size 
           if (  ( currentCarouselItem-this.getCarouselBufferSize() ) < 0  ) {
                // get next record (to left) out of carousel bounds
                var record = this.getListView().getStore().getAt( this.getCurrentListItem()-(this.getCarouselBufferSize()+1) );
           
                // if there is a record
                if (record) {
                    // add new item to start of carousel
                    var newContainer = Ext.create('Sencha.view.DictionaryDetailPageView', {sourceRecord: record});
                    this.insert(0, newContainer);
                
                    // we've added an item to the start of the array, so we need to reset our variables
                    currentCarouselItem = this.getInnerItems().indexOf( this.getActiveItem() );
                    lastCarouselItem = this.getInnerItems().length-1;
                    // if there is at least the required buffer size to the right
                    if ( (lastCarouselItem-currentCarouselItem)>(this.getCarouselBufferSize()-1)  ) {
                        // remove item from end
                        this.removeInnerAt( lastCarouselItem );
                    }
                }
           }
           
           // set current list pointer to the next item in the list
           this.setCurrentListItem( this.getCurrentListItem()-1 );
        }
           
        // store current active item for comparison next time
        this.setActiveItemTemp(  this.getInnerItems().indexOf( this.getActiveItem() ) );
           
    }
        
});